import 'dart:async';

import 'package:hive_flutter/hive_flutter.dart';
import 'package:website.core/core/domain/stores/user_store.dart';

class UserStoreImpl implements UserStore {
  const UserStoreImpl();

  @override
  Future<void> initialize({
    required List<String> modules,
  }) async {
    await Hive.initFlutter('database');

    Future openLazyBox(String module) {
      return Hive.openLazyBox(
        module,
        compactionStrategy: (entries, deletedEntries) {
          return deletedEntries >= 50;
        },
      );
    }

    final boxOpeningFutures = modules.map(openLazyBox);
    await Future.wait(boxOpeningFutures);
  }

  @override
  Future get({
    required String module,
    required String key,
  }) {
    return Hive.lazyBox(module).get(key);
  }

  @override
  Future<void> save({
    required String module,
    required String key,
    required dynamic value,
  }) async {
    await Hive.lazyBox(module).put(key, value);
  }

  @override
  Future<void> saveModuleContent({
    required String module,
    required Map moduleContent,
  }) async {
    await Hive.lazyBox(module).putAll(moduleContent);
  }

  @override
  Future<void> close() async {
    await Hive.close();
  }
}
